package com.src.xyzk_personal;

import static java.lang.Thread.sleep;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.ini4j.Ini;
import org.ini4j.Profile;
import org.json.JSONException;
import org.json.JSONObject;

import com.src.xyzk.bluetooth.BluetoothDeviceListActivity;
import com.src.xyzk.bluetooth.service.BluetoothAdapterService;
import com.src.xyzk_personal.EOL.CheryMesInfo;
import com.src.xyzk_personal.EOL.DbAdapter;
import com.src.xyzk_personal.EOL.DbAdapter.TableMain;
import com.src.xyzk_personal.UpApp.UpdateApp;
import com.src.xyzk_personal.UpApp.UpdateAppService;
import com.src.xyzk_personal.config.Common;
import com.src.xyzk_personal.config.CommonXml;
import com.src.xyzk_personal.config.Commonfunc;
import com.src.xyzk_personal.config.DeviceLicence;
import com.src.xyzk_personal.config.HttpRequest;
import com.src.xyzk_personal.config.Message;
import com.src.xyzk_personal.config.ServerSocket;
import com.src.xyzk_personal.config.WifiAdmin;
import com.src.xyzk_personal.ga1027.Eolfunctionmain;
import com.src.xyzk_personal.util.ConfigFileLoadUtil;
import com.src.xyzk_personal.util.DirectoryUnZipper;
import com.src.xyzk_personal.util.JsonFileReader;
import com.src.xyzk_personal.util.LanguageUtil;
import com.src.xyzk_personal.util.SharedPreferencesUtil;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {
    private static String TAG = "MainActivityActivity";
    Context context = MainActivity.this;
    //锁定屏幕
    private PowerManager powerManager = null;
    private WakeLock wakeLock = null;
    private EditText mEtVin = null;    //VIN码输入窗口
    private TextView mTvCarType = null;    //显示cartype
    private TextView mTvTitle = null;
    //car list
    private ListView mStationListView = null;
    private ArrayList<String> mStationList = null;
    private ListColorMainAdapter mStationListAdapter = null;
    //func list
    private ListView mStationFunctionListView = null;
    private ArrayList<String> mStationFunctionList = null;
    private ListColorAdapter mStationFunctionListAdapter = null;
    //按钮
    private Button mButClear = null;
    private Button mButOk = null;
    private Button mButMenu = null;
    private Button mButtonPrint = null;
    //记录选择
    private int mSelectStationPosition = -1;    //工位位置
    private int mSelectFunctionPosition = -1;    //功能选择
    //缓存
    SharedPreferences.Editor m_editor = null;
    SharedPreferences m_pref = null;

    private String outputDirectory = Environment.getExternalStorageDirectory().getAbsolutePath();

    String esp_code_L = "";
    String esp_code_R = "";
    //	private DbAdapter m_db = null;
    //弹出对话框
    private ProgressDialog progressdialog;
    //初始化连接service//蓝牙服务
    BluetoothAdapterService m_blueservice = BluetoothAdapterService.getInstance();
    //消息
    private static final int SHOW_ACTIVITY_RESULT = 101;

    private static final int STORAGE_PERMISSION_REQUEST_CODE = 100;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main_activity);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            // 如果权限尚未被授予，请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    STORAGE_PERMISSION_REQUEST_CODE);
        } else {
            // 权限已经被授予，继续执行你的逻辑
            initView();
        }
    }

    private void initView() {
//        if (!DirectoryUnZipper.isUnzipDone(this)) {
//            performUnzipOperation();
//        }
        LanguageUtil.setLocale(this, SharedPreferencesUtil.getString(this, SharedPreferencesUtil.LANGUAGE, "en"));
        //锁定屏幕初始化
        powerManager = (PowerManager) this.getSystemService(Service.POWER_SERVICE);
        wakeLock = this.powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Lock");
        //是否需计算锁的数量
        wakeLock.setReferenceCounted(false);
        //				m_vin.setText("LVV");
        //VIN码输入窗口初始化
        mEtVin = (EditText) findViewById(R.id.main_vin_edit);
        mTvTitle = (TextView) findViewById(R.id.main_show_title);
        //界面显示cartype
        mTvCarType = (TextView) findViewById(R.id.main_cartype);
        mTvCarType.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(context, mTvCarType.getText(), Toast.LENGTH_LONG).show();
            }
        });

        //初始化CarList
        mStationListView = (ListView) findViewById(R.id.main_show_car);
        mStationList = new ArrayList<String>();
        mStationListAdapter = new ListColorMainAdapter(mStationList);
        mStationListView.setAdapter(mStationListAdapter);
        //初始化FuncList
        mStationFunctionListView = (ListView) findViewById(R.id.main_show_func);
        mStationFunctionList = new ArrayList<String>();
        mStationFunctionListAdapter = new ListColorAdapter(mStationFunctionList);
        mStationFunctionListView.setAdapter(mStationFunctionListAdapter);
        Common.Printnum = SharedPreferencesUtil.getInt(getApplicationContext(), "intValueKey", 0);
        //list点击事件
        mStationListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long arg3) {
                autoExecuteEol(position, true);
            }
        });
        //函数选择事件
        mStationFunctionListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long arg3) {
                if (Common.cartype.OptMode == 0) //自动时，不能点击该列表
                {
                    Toast.makeText(context, R.string.main_tip_text5, Toast.LENGTH_SHORT).show();
                    return;
                }
                mSelectFunctionPosition = position;
                mStationFunctionListAdapter.setSelected(position);
                mStationFunctionListAdapter.notifyDataSetChanged();
                //执行
                startDiagnose(mSelectStationPosition, "STR");
            }
        });
        //OK按钮
        mButOk = (Button) findViewById(R.id.main_but_ok);
        mButOk.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //开始执行新流程
                //先清除显示
                ClearData();
                //第一步，扫描VIN
                enterVinCode();
            }
        });
        mButMenu = (Button) findViewById(R.id.main_opt_menu);
        mButtonPrint = (Button) findViewById(R.id.main_but_print);
        registerForContextMenu(mButMenu);
        //print按钮
        mButtonPrint = (Button) findViewById(R.id.main_but_print);
        mButtonPrint.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                queryForVin();
            }
        });
        //检查设备非法状态
        DeviceLicence licence = new DeviceLicence();
        if (!licence.CheckDevice(context)) {
            finish();
        }
        Common.Lang = SharedPreferencesUtil.getString(this, SharedPreferencesUtil.LANGUAGE, "zh");
        //设置标题
        mTvTitle.setText(getString(R.string.app_name) + " - " + getVersionName(this));
        //获取车型列表
        LoadmesConfig();
        m_editor = this.getSharedPreferences("config", MODE_PRIVATE).edit(); //不存在则创建
        m_pref = getSharedPreferences("config", MODE_PRIVATE);
        //获取通讯方式缓存
        Common.Communication = m_pref.getInt("Communication", 0);

        //启动软件更新查询服务
        Intent it = new Intent(this, UpdateAppService.class);
        startService(it);
        updateApp();
    }

    public String getVersionName(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void updateApp() {
        Boolean dialog_isok = Common.dialog_isok;
        SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.app_name), MODE_PRIVATE);//拿到 sharedPreferences 的引用 MODE_PRIVATE表示只能被本应用读写，不能被其他应用读写
        Boolean version_isok = false;
        String appVersion = sharedPreferences.getString("Version", "V1.1");
        Float oldVersion = Float.parseFloat(getVersionName(this));
        try {
            float newVersion = Float.parseFloat(appVersion.substring(1));
            if (newVersion > oldVersion) {
                version_isok = true;
            } else {
                version_isok = false;
                return;
            }
            Log.i(TAG, "newVersion = " + newVersion + "oldVersion = " + oldVersion);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        if (version_isok && dialog_isok) {
            final UpdateApp dialog = new UpdateApp(MainActivity.this);
            dialog.show();
            Common.dialog_isok = false;
        }
    }

    private void Sleep(int i) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_activity, menu);
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //请求常亮
        wakeLock.acquire();
        changeButtonLanguage();
    }

    private void changeButtonLanguage() {
        mButOk.setText(R.string.but_scan);
        mButMenu.setText(R.string.options);
        mButtonPrint.setText(R.string.print_again);
    }

    //自动执行初始化功能
    void autoExecuteEol(int item, boolean isShowTipDialog) {
        //这里来查看是否获取到了ESP配置码，如果没有就输入
        Common.DeFault_Eol = item;
        boolean isespok = false;
        if (Common.cartype.getMap("ESP") > 0 && (Common.cartype.getMap("EPB_D") == 1) && Common.DeFault_Eol == 0) //带ESP功能
        {
            //先检查是否已经输入过了
            byte[] espbyte = Common.cartype.getMapByte("ESP");
            if (espbyte != null)
                isespok = true;
			/*
			else
			{
				//String v_esp = HttpRequest.sendRequestWithHttpURLConnection(new String(Common.cartype.vin), Common.Mes_esp + "/ESPBrakeInfoRecords");
				//String v_esp = HttpRequest.sendRequestWithHttpURLConnection("LNN6RMBE7LF511440", Common.Mes_esp + "/ESPBrakeInfoRecords");

			}
			*/
            String v_esp = "";
            if (Common.cartype.mesinfo != null)
                v_esp = Common.cartype.mesinfo.esp_code;
            int v_adr = 0;
            if (v_esp != null)
                v_adr = v_esp.indexOf("/", 0);
            //if(v_esp != null)
            //	v_adr = v_esp.indexOf("信息 ");
            if (v_adr > 0) //找到//B20526GNMHKE05870/B30516GNMG1E202E0
            {
                int v_end = v_esp.indexOf("/", 0);
                if (v_end > 0) {
                    esp_code_L = v_esp.substring(0, v_end);
                    if (v_esp.length() >= v_end + 1 + 17)
                        esp_code_R = v_esp.substring(v_end + 1, v_end + 1 + 17);
                    else
                        esp_code_R = null;
                }
                if (esp_code_L != null && esp_code_R != null) {
                    if (esp_code_L.length() == 17 && esp_code_R.length() == 17) {
                        isespok = checkespCode(esp_code_L, esp_code_R);
                    }
                }
            } else  //先检查是否已经输入过了
            {
                if (esp_code_L != null && esp_code_R != null) {
                    if (esp_code_L.length() == 17 && esp_code_R.length() == 17) {
                        isespok = checkespCode(esp_code_L, esp_code_R);
                    }
                }
            }
            if (!isespok) {
                StartInputEspConfigL();
                return;
            }
        }
        mSelectStationPosition = item;
        mStationListAdapter.setSelected(item);
        mStationListAdapter.notifyDataSetChanged();
        LoadFunction(item);
        if (Common.cartype.OptMode == 0) //自动时，直接执行
        {

            //最后提示
            final MsgWaitDialog waitdialog = new MsgWaitDialog(MainActivity.this);
            waitdialog.setText(getResources().getString(R.string.implement) + "：" + mStationList.get(item) + "?");
            waitdialog.setWaitTime(0);
            waitdialog.ShowCancel();
            if (isShowTipDialog) {
                waitdialog.show();
            } else {
                waitdialog.dismiss();
            }
            waitdialog.setOnOKButton(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    waitdialog.dismiss();
                    startDiagnose(mSelectStationPosition, "STR");
                }
            });
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //取消屏幕常亮
        wakeLock.release();
    }

    @Override
    protected void onDestroy() {
        m_blueservice.StopService();
        super.onDestroy();
        //m_db.close();

    }

    @Override
    public void finish() {
        m_blueservice.StopService();
        super.finish();
    }

    @SuppressLint("HandlerLeak")
    private final Handler mhander = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == Message.MSG_Main_GetVersion) {
                if (msg.arg1 != 100)
                    progressdialog.dismiss();
                m_blueservice.m_log.PrintAppend("GetMsg:" + msg.arg1 + "," + msg.arg2 + "," + (String) msg.obj);
                if (msg.arg1 == 1) //ok
                {
                    if (msg.arg2 == 1) {
                        LoadStation((String) msg.obj, Common.cartype.carmode_dir);
                    } else {
                        StartSelectCarmode(null);
                    }
                } else if (msg.arg1 == 100) {
                    progressdialog.setMessage("获取PIN码&TPMS数据...");
                } else {
                    Toast.makeText(context, "获取PIN&TPMS数据失败", Toast.LENGTH_LONG).show();
                    if (Common.cartype.carmode_dir != null && Common.cartype.carmode_dir.length() > 1)
                        LoadStation((String) msg.obj, Common.cartype.carmode_dir);
                    else
                        StartSelectCarmode(null);
                }
            }
        }

        ;
    };

    //是否联网
    public void connectInternet() {


    }

    //清除数据
    private void ClearData() {
        //先清除显示
        mEtVin.setText("");
        mTvCarType.setText("");
        mStationListAdapter.setSelected(-1);
        mStationList.clear();
        mStationListAdapter.notifyDataSetChanged();
        mStationFunctionList.clear();
        mStationFunctionListAdapter.notifyDataSetChanged();
    }

    //获取WIFI连接状况
    boolean GetWifiConnect() {
        WifiAdmin m_wifi = new WifiAdmin(context);
        if (m_wifi.getState() < 2) //已经关闭，则打开
        {
            Toast.makeText(context, R.string.main_tip_text7, Toast.LENGTH_SHORT).show();
            return false;
        }
        String ConnectName = m_wifi.getWifiConnectSSID();
        if (ConnectName == null) {
            Toast.makeText(context, R.string.main_tip_text8, Toast.LENGTH_SHORT).show();
            return false;
        }
        if (ConnectName.equals(Common.BoxName))
            return true;
        else {
            Toast.makeText(context, R.string.main_tip_text8, Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    //获取系统设置
    private void LoadmesConfig() {
        //结果初始化
        Ini inifile;
        try {
            String configFile = Common.Dir + Common.GuestName + "/mes.ini";

            inifile = new Ini(new File(configFile));
            Profile.Section sec = null;
            //获取系统配置信息
            sec = inifile.get("SETTING");
            String v_webenable = sec.get("WEB_ENABLE");
            Common.web_enable = "1".equals(v_webenable);
            Common.web_ip = "http://" + sec.get("IP");
            Common.web_mes = Common.web_ip + sec.get("WEBVersion");
            Common.Mes_version = Common.web_mes;
//            Common.web_API_SelectUpdate = Common.web_ip + sec.get("WEB1");
//            Common.web_API_AppUpdate = Common.web_ip + sec.get("WEB2");
            Common.web_updata = Common.web_ip + sec.get("WEB3");
            Common.web_API_File = Common.web_ip + sec.get("WEB4");
            Common.web_API_AppStatus = Common.web_ip + sec.get("WEB5");
            Common.web_API_SelectPinforVin = Common.web_ip + sec.get("WEB6");
            Common.web_API_SelectHeat = Common.web_ip + sec.get("WEB7");
            Common.web_GetTPMS = Common.web_ip + sec.get("web_GetTPMS");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //开始执行流程,输入VIN
    private void enterVinCode() {
        final InputVinDialog dialog = new InputVinDialog(this);
        esp_code_L = "";
        esp_code_R = "";
//        dialog.setEditString("EC3DEUFD6R0000003");
        dialog.setOnOKButton(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String vin = dialog.GetEditString();
                if (!Commonfunc.CheckVinFormat(vin.getBytes())) {
                    Toast.makeText(context, getString(R.string.msg_show_context14), Toast.LENGTH_SHORT).show();
                    dialog.setEditString("");
                    return;
                } else { //输入配置代码
                    Common.cartype.tcu_file_len = 0;
                    m_blueservice.StopService();
                    BluetoothAdapterService.m_blue_state.SetListen();
                    Common.cartype.clearall();
                    Common.cartype.setVin(vin);
                    dialog.dismiss();
                    mEtVin.setText(vin);
                    m_blueservice.m_log.startRecord(vin);
                    //记录软件版本
                    BluetoothAdapterService.getInstance().m_log.PrintLog(context.getString(R.string.Version));
                    //弹出对话框，开启线程
                    progressdialog = ProgressDialog.createDialog(context, "获取MES信息...");
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            try {
                                GetCheryVersion();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                }
            }
        });
        dialog.show();
    }

    void GetCheryVersion() throws JSONException {
        boolean isok = false;
        String softcode = "";
        String vin = new String(Common.cartype.vin);
        for (int k = 0; k < 3; k++) {
            //String version = HttpRequest.sendRequestWithHttpURLConnection(vin, Common.Mes_version);// + "/Get_Electric");
            JSONObject obj = new JSONObject();
            obj.put("vin", vin);
            m_blueservice.m_log.PrintLog("MesAdr:" + Common.Mes_version);
			String version = HttpRequest.sendRequestPost(Common.Mes_version,obj.toString());
//            String version = JsonFileReader.loadJSONFromAsset(this, "data.json");
            m_blueservice.m_log.PrintLog("MesReturn:" + version);

            Common.cartype.mesinfo = CommonXml.GetEcuInfofromECOS(version);
            softcode = Common.cartype.mesinfo.getSoftCode();
            Commonfunc.StringToBytes(Common.cartype.mesinfo.PinCode, Common.cartype.pin, 4);
            if ((softcode != null) && softcode.length() < 10) //获取到了
            {
                isok = false;
                m_blueservice.m_log.PrintAppend("Mes SoftCode:" + softcode);
                break;
            } else
                isok = true;
        }
        int Pmsg = 0;  //1--获取数据成功，2--获取失败。
        String config = "";
        if (isok) {
            m_blueservice.m_log.PrintAppend("jiexi data.");
            config = Common.cartype.mesinfo.getSoftCode();
            config = config.trim();
            String cartype = Common.cartype.mesinfo.getCarType();
            if (config.length() == 252) //JX65
            {
                Common.cartype.carmode_dir = "JX65";
                m_blueservice.m_log.PrintAppend("Car Dir:" + Common.cartype.carmode_dir);
                Pmsg = 1;
            } else if (cartype.equals("F01")) //CX62
            {
                Common.cartype.carmode_dir = "CX62";
                if (config.length() != 16) {
                    m_blueservice.m_log.PrintAppend("获取MES配置失败");
                    Pmsg = 2;
                } else {
                    Pmsg = 1;
                }
            } else {
                if (config.length() >= 16) {
                    Pmsg = 2;
                } else {
                    Pmsg = 2;
                }
            }

        }
        int isconfig = 1;
        //获取配置信息

        mhander.obtainMessage(Message.MSG_Main_GetVersion, isconfig, Pmsg, config).sendToTarget();
    }

    //扫描配置二维码
    private void StartInputConfig(final String car) {
        final InputConfigDialog dialog = new InputConfigDialog(this);
        //dialog.setEditString("1400001010240012");
        //dialog.setEditString("EF9DB9F9B1AD0AF3008042000300180300680000000000000000000000000000");
        //dialog.setEditString("EF9DB9F9B1AD0AB370B06B00A50018E3007C0000000000000000000000000000");
        //dialog.setEditString("EFBFBFB9B1ED029173005000030118570048040053982002020000000000000090FD0300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
//        dialog.setEditString("AF9FBFB9F1ED02B333305200C30118E7205C0400535820071200000000000000960704C3006300000000000000000000000000000000000000000000000000000000A401AE90600C003633300000C3E900E4201C00014000000790F3E30B1C00000000000000000000000000000000000000000000000000000000000000");//JX65 6DCT
        //dialog.setEditString("6FBFB1B991ED02911330500003011857004A0400139A2002020000000000000080040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
        //dialog.setEditString("FF3FB9B9B1E717D73372D22002091857186A049C309820041A0000000000000080050400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");  //JX65 PHEV E+科技版
        //dialog.setEditString("7F3FA1E991E717870342D220020818771868049E309820060A0000000000000080040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); //JX65PHEV e+运动版
        dialog.setOnOKButton(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String config = dialog.GetEditString();
                if (config.length() != 16 && config.length() != 64 && config.length() != 252) {
                    Toast.makeText(context, getString(R.string.msg_show_context15), Toast.LENGTH_SHORT).show();
                    dialog.setEditString("");
                    return;
                } else if (config.length() == 16) {
                    if (car.equals("CX62B")) //只能是64位
                    {
                        Toast.makeText(context, getString(R.string.msg_show_context15), Toast.LENGTH_SHORT).show();
                        dialog.setEditString("");
                        return;
                    } else if (car.equals("KQ71EV")) {
                        dialog.dismiss();
                        LoadStation(config, car);
                    } else if (car.equals("CX62")) {
                        dialog.dismiss();
                        LoadStation(config, car);
                    }
                } else {
                    if (config.charAt(6) > 0x37) {
                        Toast.makeText(context, "未从服务器获取到PIN码", Toast.LENGTH_LONG).show();
//						return;//未获取到PIN码
                        //Common.cartype.pin[0] = 0x30;
                        //Common.cartype.pin[1] = 0x31;
                        //Common.cartype.pin[2] = 0x32;
                        //Common.cartype.pin[3] = 0x33;
                    }
                    dialog.dismiss();
                    //StartSelectCarmode(config);
                    LoadStation(config, car);
                }
            }
        });
        dialog.show();
    }

    private void StartInputEspConfigL() {
        final InputConfigDialog dialog = new InputConfigDialog(this);
        if (esp_code_L != null)
            dialog.setEditString(esp_code_L);
//        dialog.setEditString("B2123456789012345");
        dialog.setTitle(R.string.scan_left_traceability_barcode);
        dialog.setOnOKButton(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String espL = dialog.GetEditString();
                if (espL == null || espL.length() != 17) {
                    Toast.makeText(context, "条码长度不对", Toast.LENGTH_SHORT).show();
                    dialog.setEditString("");
                    return;
                } else {
                    if (espL.indexOf("B2") < 0) {
                        Toast.makeText(context, "条码信息输入错误!", Toast.LENGTH_SHORT).show();
                        dialog.setEditString("");
                        return;
                    } else
                        esp_code_L = espL;
                    dialog.dismiss();
                    StartInputEspConfigR();
                }
            }
        });
        dialog.show();
    }

    private void StartInputEspConfigR() {
        final InputConfigDialog dialog = new InputConfigDialog(this);
        if (esp_code_R != null)
            dialog.setEditString(esp_code_R);
//        dialog.setEditString("B3123456789012345");
        dialog.setTitle(getResources().getString(R.string.scan_right_traceability_barcode));
        dialog.setOnOKButton(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String espR = dialog.GetEditString();
                if (espR.length() != 17) {
                    Toast.makeText(context, "条码长度不对", Toast.LENGTH_SHORT).show();
                    dialog.setEditString("");
                    return;
                } else {
                    if (espR.indexOf("B3") < 0) {
                        Toast.makeText(context, "条码信息输入错误!", Toast.LENGTH_SHORT).show();
                        dialog.setEditString("");
                        return;
                    } else
                        esp_code_R = espR;
                    dialog.dismiss();
                    if (checkespCode(esp_code_L, esp_code_R))
                        autoExecuteEol(Common.DeFault_Eol, false);
                }
            }
        });
        dialog.show();
    }

    private boolean checkespCode(String espL, String espR) {
        boolean isok = false;
        //左边是B2，右边是B3,都是17位
        if (espL.length() != 17 || espR.length() != 17)
            return false;
        if (!espL.contains("B2") || !espR.contains("B3"))
            return false;
        //查找配置码
        String v_spidL = espL.substring(5, 8);
        String v_spidR = espR.substring(5, 8);
        if (!v_spidL.equals(v_spidR))
            return false;
        byte[] v_esp = new byte[1];
        if (v_spidL.equals("6GN"))
            v_esp[0] = 0x00;
        else if (v_spidL.equals("3JS"))
            v_esp[0] = 0x01;
        else if (v_spidL.equals("6CJ"))
            v_esp[0] = 0x02;
        else
            v_esp[0] = (byte) 0xFF;
        Common.cartype.putMapbyte("ESP", v_esp);
        isok = true;
        return isok;
    }

    private int getPinAndPepsConfig(String config) {
        int isok = 0;
        //先判断是否有PIN了
        if (((Common.cartype.pin[0] | Common.cartype.pin[1]) != 0) && ((Common.cartype.tpms[3] | Common.cartype.tpms[7] | Common.cartype.tpms[11]) != 0)) {
            isok = 1;
            return isok;
        }
        //在这里判断是否PHEV车型
        String pvin = "2:";
        if (Common.cartype.carmode_dir != null && Common.cartype.carmode_dir.equals("JX65PHEV"))
            pvin += new String(Common.cartype.vin) + "," + "PHEV:" + Common.cartype.mesinfo.GBSN + ";";
        else
            pvin += new String(Common.cartype.vin) + "," + "GetPinCode;";
        pvin = String.valueOf(100000 + pvin.getBytes().length).substring(1, 6) + pvin;
        ServerSocket v_server = new ServerSocket();
        byte[] pin = new byte[0x900];
        Arrays.fill(pin, (byte) 0);
        if (v_server.ConnectServer(Common.Server_IP1, Common.Server_PORT)) {
            int len = 0;
            int k = 0;
            String getdata = "";
            for (k = 0; k < 5; k++) {
                len = v_server.SearchVinConfigFromConfigDb(pvin, pin, pin.length);
                if (len < 0x10) //bao报错
                {
                    if (k > 5)
                        return isok;
                    else
                        Sleep(100);
                } else   //判断结果
                {
                    getdata = new String(pin);
                    if (getdata.indexOf("ok") > 0)
                        break;
                }
                Sleep(200);
            }
            if (k > 5) {
                return isok;
            } else {//2:05517018,52F831,20190907;
                String[] vpin = getdata.split(",");
                m_blueservice.m_log.PrintAppend("PIN:" + vpin[0]);
                Commonfunc.StringToBytes(vpin[0].substring(2), Common.cartype.pin, 4);
                //tpms
                m_blueservice.m_log.PrintAppend("TPMS:" + vpin[1] + "," + vpin[2] + "," + vpin[3] + "," + vpin[4]);
                if ((vpin[1].length() + vpin[2].length() + vpin[3].length() + vpin[4].length()) == 32) {
                    byte[] v_id = new byte[4];
                    for (int s = 0; s < 4; s++) {
                        Commonfunc.StringToBytes(vpin[s + 1], v_id, 4);
                        System.arraycopy(v_id, 0, Common.cartype.tpms, s * 4, 4);
                    }
                    isok = 1;
                } else {
                    m_blueservice.m_log.PrintAppend("获取TPMS失败!");
                    //return isok;
                }

                if (Common.cartype.carmode_dir != null && Common.cartype.carmode_dir.equals("JX65PHEV")) {
                    vpin[5] = vpin[5].trim();
                    int getlen = Commonfunc.StringToBytes(vpin[5], Common.cartype.tcu_file, 0x400);
                    if (getlen >= 0) {
                        Common.cartype.tcu_file_len = getlen;
                        m_blueservice.m_log.PrintAppend("TCU:" + vpin[5]);
                        isok = 1;
                    } else {
                        Common.cartype.tcu_file_len = 0;
                        return isok;
                    }
                } else {
                    Commonfunc.StringToBytes(vpin[5], Common.cartype.PEPS, 3);
                    m_blueservice.m_log.PrintAppend("PEPSConfig:" + vpin[5]);
                }
                return isok;
            }
        }
        return isok;
    }

    //先列举出来所有车型文件夹
    private void StartSelectCarmode(final String str) {
        List<String> filelist = Commonfunc.GetDictionarySonList(Common.Dir + Common.GuestName);
        if (filelist.size() == 1) {
            Common.cartype.carmode_dir = filelist.get(0);
            if (str != null)
                LoadStation(str, Common.cartype.carmode_dir);
            else
                StartInputConfig(Common.cartype.carmode_dir);
        } else {
            final SelectCarDialog dialogconfig = new SelectCarDialog(this);
            for (int i = 0; i < filelist.size(); i++) {
                dialogconfig.AddSelectString(filelist.get(i));
            }
            dialogconfig.SetDefaultSelect(m_pref.getInt("CAR", 0));
            dialogconfig.setOnOKButton(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    String carname = dialogconfig.GetSelectString();
                    Common.cartype.carmode_dir = carname;
                    dialogconfig.dismiss();
                    //缓存
                    m_editor.putInt("CAR", dialogconfig.GetSelected());
                    m_editor.commit();
                    if (str != null)
                        LoadStation(str, carname);
                    else
                        StartInputConfig(carname);
                }
            });
            dialogconfig.show();
        }
    }

    @SuppressLint("SetTextI18n")
    private void LoadStation(String config, String carname) {
        Common.cartype.SetCartype(carname, config, context);
        if (Common.cartype.mesinfo == null)
            Common.cartype.mesinfo = new CheryMesInfo();
        if (Common.configmode == 0) {
            mTvCarType.setText(carname); //设置显示
        } else {
            mTvCarType.setText(carname + "[" + config + "]"); //设置显示
			/*if(getPinAndPepsConfig(config))
			{
				Toast.makeText(context,"未从服务器获取到PIN码", Toast.LENGTH_LONG).show();
				return;//未获取到PIN码
			}*/
        }

        //load工位选择
        Ini inifile = null;
        try {
            String configFile = LanguageUtil.changeConfigFile();
            Log.i(TAG, "LoadStation: " + configFile);
            inifile = new Ini(new File(configFile));
            Profile.Section sec = inifile.get("STATION");
            int num = Integer.parseInt(sec.get("NUM"));
            String id;
            for (int i = 0; i < num; i++) {
                id = "T" + i;
                mStationList.add(sec.get(id));
            }
            mStationListAdapter.notifyDataSetChanged();

        } catch (IOException e) {
            e.printStackTrace();
        }
        if (inifile != null) {
            if (mStationList.size() <= 1) return;
            autoExecuteEol(Common.DeFault_Eol, true);
        }
    }

    //获取需要执行的函数列表
    private void LoadFunction(int stationPosition) {
        mSelectFunctionPosition = -1;    //初始化
        mStationFunctionList.clear();
        mStationFunctionListAdapter.setSelected(-1);
        if (stationPosition == 4)
            Common.cartype.OptMode = 1;
        else
            Common.cartype.OptMode = 0;
        //获取初始化列表
        if (Common.cartype.OptMode == 1) {
            ArrayList<String> list = Eolfunctionmain.GetStepInformationRepair(this);
            mStationFunctionList.addAll(list);
            mStationFunctionListView.setClickable(true);
        } else {
            String stepName = ConfigFileLoadUtil.getStepFilePath(stationPosition, Common.cartype.carmode_dir);
            //load step
            ArrayList<String> list = Eolfunctionmain.GetStepInformation(stepName);
            mStationFunctionList.addAll(list);
            if (Common.cartype.OptMode == 0) //自动执行,则不能点击
            {
                mStationFunctionListView.setClickable(false);
            }
        }
        mStationFunctionListAdapter.notifyDataSetChanged();
    }

    /**
     * 获取pin码和PEPS配置码
     *
     * @return 是否从上位机获取到
     */
    private boolean GetPinfromWebservice() {
        byte[] pinCheck = new byte[8];
		/*if(!Arrays.equals(pinCheck, Common.cartype.pin))
		{//不是0000,PIN码
			m_blueservice.m_log.PrintLog("Have Pin:" + Commonfunc.bytesToHexStringP(Common.cartype.pin,0,4));// 已获取，不需要再获取了
			return true;
		}*/
        boolean result_isok = false;
        String queryvin = "resultVin=" + new String(Common.cartype.vin);
        String querypin = null;
        m_blueservice.m_log.PrintLog("Pin adr=" + Common.web_GetPin + "?" + queryvin);
        for (int i = 0; i < 3; i++) {
            querypin = HttpRequest.sendGet(Common.web_GetPin, queryvin); //查询pin码
            System.out.println(querypin);
            if (querypin.indexOf("200") > 0) {
                break;
            }
        }
        if (!querypin.isEmpty() && querypin.indexOf("200") > 0) {
            try {
                JSONObject jsonObject = new JSONObject(querypin);
                JSONObject result = jsonObject.getJSONObject("data");
                //获取返回的pin码
                // TODO
                Commonfunc.StringToBytes(result.getString("PIN"), Common.cartype.pin, Common.cartype.pin.length);
                m_blueservice.m_log.PrintAppend("GetPin:" + result.getString("PIN"));
                result_isok = true;
            } catch (JSONException e) {
                System.out.println("----获取pin码异常-----" + e);
                m_blueservice.m_log.PrintAppend("GetPin:" + e.toString());
                e.printStackTrace();
                result_isok = false;
            }
        } else {
            m_blueservice.m_log.PrintLog("GetPin failed->" + querypin.toString());
            result_isok = false;
        }

        return result_isok;
    }

    private boolean GetTpmsfromWebservice() {
        byte[] tpmsid = new byte[16];
        if (!Arrays.equals(tpmsid, Common.cartype.tpms)) {//不是0000,PIN码已获取，不需要再获取了
            return true;
        }

        boolean result_isok = false;
        String queryvin = "resultVin=" + new String(Common.cartype.vin);
        String querypin = null;
        for (int i = 0; i < 3; i++) {
            querypin = HttpRequest.sendGet(Common.web_GetTPMS, queryvin); //查询pin码
            System.out.println(querypin);
            if (querypin.indexOf("200") > 0) {
                break;
            }
        }
        if (!querypin.isEmpty() && querypin.indexOf("200") > 0) {
            try {
                JSONObject jsonObject = new JSONObject(querypin);
                JSONObject result = jsonObject.getJSONObject("data");
                //获取返回的pin码
                // TODO
                byte[] v_id = new byte[4];
                Commonfunc.StringToBytes(result.getString("flId"), v_id, 4);
                System.arraycopy(v_id, 0, Common.cartype.tpms, 0, 4);
                Commonfunc.StringToBytes(result.getString("frId"), v_id, 4);
                System.arraycopy(v_id, 0, Common.cartype.tpms, 4, 4);
                Commonfunc.StringToBytes(result.getString("rlId"), v_id, 4);
                System.arraycopy(v_id, 0, Common.cartype.tpms, 8, 4);
                Commonfunc.StringToBytes(result.getString("rrId"), v_id, 4);
                System.arraycopy(v_id, 0, Common.cartype.tpms, 12, 4);
                m_blueservice.m_log.PrintAppend("flid:" + result.getString("flId") + " " +
                        "frId:" + result.getString("frId") + " " +
                        "rlId:" + result.getString("rlId") + " " +
                        "rrId:" + result.getString("rrId"));
                result_isok = true;
            } catch (JSONException e) {
                System.out.println("----获取TPMS异常-----" + e);
                e.printStackTrace();
                result_isok = false;
            }
        } else {
            result_isok = false;
        }

        return result_isok;
    }

    private boolean GetTcufilefromWebservice() {
        byte[] tcu = new byte[0x410];
        if (!Arrays.equals(tcu, Common.cartype.tcu_file)) {//不是0000,PIN码已获取，不需要再获取了
            return true;
        }

        boolean result_isok = false;
        String queryvin = "filename=" + Common.cartype.mesinfo.GBSN + ".bin";
        String querypin = null;
        for (int i = 0; i < 3; i++) {
            querypin = HttpRequest.sendGet(Common.web_GetTCU, queryvin); //查询pin码
            System.out.println(querypin);
            if (querypin.indexOf("200") > 0) {
                break;
            }
        }
        if (!querypin.isEmpty() && querypin.indexOf("200") > 0) {
            try {
                JSONObject jsonObject = new JSONObject(querypin);
                String tcufile = jsonObject.get("msg").toString();
                //获取返回的pin码
                // TODO
                if (Commonfunc.StringToBytes(tcufile, Common.cartype.tcu_file, Common.cartype.tcu_file.length) == 0x400) {
                    result_isok = true;
                    Common.cartype.tcu_file_len = 0x400;

                }
                m_blueservice.m_log.PrintAppend("TCU file:" + tcufile);

            } catch (JSONException e) {
                System.out.println("----获取pin码异常-----" + e);
                e.printStackTrace();
                result_isok = false;
            }
        } else {
            result_isok = false;
        }

        return result_isok;
    }

    //开始诊断 selectfunc -- 执行项
    private void startDiagnose(int selectfunc, String funcname) {
        //先检查WIFI连接情况
        //if(GetWifiConnect() == false) return;
        String station = mStationList.get(mSelectStationPosition);
		/*boolean r_flash = false;
		if(m_select_func >= 0)
		{
			if(m_listfunc_data.get(m_select_func).indexOf("刷写")  == 0)
				r_flash = true;
		}
		if((station.indexOf("刷写工位") > 0) || r_flash == true)
		{
			Common.Flash = true;
		}
		else
		{
			Common.Flash = false;
			if(ConnectBluetooth() == false) return;
		}
		*/
        if (Common.Communication == 0) //blue
        {
            m_blueservice.m_log.printMessage("Use bluetooth,connect to box.");
            if (!ConnectBluetooth()) return;
        } else {
            m_blueservice.m_log.printMessage("Use cable");
        }
        Bundle bund = new Bundle();
        if (mSelectFunctionPosition >= 0) //返修功能
        {
            bund.putString("TITLE", mStationList.get(mSelectStationPosition) + "->" + mStationFunctionList.get(mSelectFunctionPosition));
            String v_funcname = Common.cartype.SetRepairIstep(mStationFunctionList.get(mSelectFunctionPosition), this);
            bund.putString("FUNC_NAME", v_funcname);
        } else {
            bund.putString("TITLE", mStationList.get(mSelectStationPosition));
            bund.putString("FUNC_NAME", "");
        }
        Common.cartype.station = mSelectStationPosition;
        bund.putInt("CAR", mSelectStationPosition);
        bund.putInt("FUNC", mSelectFunctionPosition);
        bund.putString("DIR", ConfigFileLoadUtil.getStepFilePath(mSelectStationPosition, Common.cartype.carmode_dir));
        Intent newintent = new Intent(context, EolNewFunctionActivity.class);
        newintent.putExtras(bund);
        startActivity(newintent);
    }

    //屏蔽返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {    //返回键
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //系统菜单处理方法
    @SuppressLint("NonConstantResourceId")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.main_setting_system:    //系统设置
                Intent newintent = new Intent(this, SettingActivity.class);
                startActivity(newintent);
                break;
            case R.id.main_setting_DBdata:    //数据管理
                Intent DBintent = new Intent(this, UpdateDataActivity.class);
                startActivity(DBintent);
                break;
            case R.id.main_setting_about:    //about
                LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                assert inflater != null;
                @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.main_alertdiag_title, null);
                new AlertDialog.Builder(MainActivity.this)
                        .setCustomTitle(view)
                        .setMessage(R.string.my_about)
                        .setPositiveButton(R.string.but_ok, null)
                        .show();
                break;
            case R.id.main_settings_exit:    //exit
                m_blueservice.StopService();
                System.exit(0);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //系统菜单处理方法
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getMenuInflater().inflate(R.menu.main_activity, menu);
        //registerForContextMenu(v);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        return onOptionsItemSelected(item);
    }


    //蓝牙连接
    private boolean ConnectBluetooth() {
        if (BluetoothAdapterService.m_blue_state.IsConnected() == true) return true;
        Bundle bund = new Bundle();
        bund.putString("BOX", Common.BoxName);
        Intent intent = new Intent(context, BluetoothDeviceListActivity.class);
        intent.putExtras(bund);
        startActivityForResult(intent, SHOW_ACTIVITY_RESULT);
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SHOW_ACTIVITY_RESULT:
                if (resultCode == BluetoothDeviceListActivity.RESULT_OK) {
                    startDiagnose(mSelectStationPosition, "STR");
                }
                break;
        }
    }

    public class ListColorAdapter extends BaseAdapter {
        private ArrayList<String> listdata = null;
        private ListColor listlayout = null;
        private View view = null;
        private LayoutInflater inflater = null;
        private int Selected = -1;

        public ListColorAdapter(ArrayList<String> Pdata) {
            listdata = Pdata;
        }

        @Override
        public int getCount() {
            if (listdata != null)
                return listdata.size();
            else
                return 0;
        }

        @Override
        public Object getItem(int position) {
            if (listdata != null && listdata.size() > position)
                return listdata.get(position);
            else
                return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void setSelected(int pos) {
            Selected = pos;
        }

        public int getSelected() {
            return Selected;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.listcoloritem, null, false);
            listlayout = (ListColor) view.getTag();
            if (listlayout == null) {
                listlayout = new ListColor();
                listlayout.text = (TextView) view.findViewById(R.id.eolfunction_liststep_context);
                view.setTag(listlayout);
            }
            if (position == Selected) {
                //listlayout.text.setBackgroundColor(Color.GREEN);
                view.setBackgroundColor(Color.GREEN);
                listlayout.text.setSelected(true);
                listlayout.text.setPressed(true);
            } else if (position % 2 == 1) {
                listlayout.text.setSelected(false);
                listlayout.text.setPressed(false);
                view.setBackgroundColor(0xFFC0C0C0);
            } else {
                listlayout.text.setSelected(false);
                listlayout.text.setPressed(false);
                view.setBackgroundColor(Color.WHITE);
            }
            listlayout.text.setText(listdata.get(position));
            return view;
        }
    }

    public class ListColorMainAdapter extends BaseAdapter {
        private ArrayList<String> listdata = null;
        private ListColor listlayout = null;
        private View view = null;
        private LayoutInflater inflater = null;
        private int Selected = -1;

        public ListColorMainAdapter(ArrayList<String> Pdata) {
            listdata = Pdata;
        }

        @Override
        public int getCount() {
            if (listdata != null)
                return listdata.size();
            else
                return 0;
        }

        @Override
        public Object getItem(int position) {
            if (listdata != null && listdata.size() > position)
                return listdata.get(position);
            else
                return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void setSelected(int pos) {
            Selected = pos;
        }

        public int getSelected() {
            return Selected;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.listcoloritemmain, null, false);
            listlayout = (ListColor) view.getTag();
            if (listlayout == null) {
                listlayout = new ListColor();
                listlayout.text = (TextView) view.findViewById(R.id.eolfunction_liststep_main);
                view.setTag(listlayout);
            }
            if (position == Selected) {
                view.setBackgroundColor(Color.GREEN);
                listlayout.text.setSelected(true);
                listlayout.text.setPressed(true);
            } else if (position % 2 == 1) {
                listlayout.text.setSelected(false);
                listlayout.text.setPressed(false);
                view.setBackgroundColor(0xFFC0C0C0);
            } else {
                listlayout.text.setSelected(false);
                listlayout.text.setPressed(false);
                view.setBackgroundColor(Color.WHITE);
            }
            listlayout.text.setText(listdata.get(position));
            return view;
        }
    }

    class ListColor {
        TextView text;
    }


    /**
     * VIN查询
     *
     * @param isShowQuery 是否显示查询数据
     */
    public void queryForVin() {
        final InputVinDialog dialog = new InputVinDialog(this);
        //dialog.setEditString("LVUDB21B1KF000364");
        dialog.setOnOKButton(new OnClickListener() {

            @Override
            public void onClick(View v) {
                final String vin = dialog.GetEditString();
                if (!Commonfunc.CheckVinFormat(vin.getBytes())) {
                    Toast.makeText(MainActivity.this, "请输入正确的VIN码", 0).show();
                    dialog.setEditString("");
                    return;
                } else {
                    dialog.dismiss();
                    DbAdapter db = new DbAdapter(MainActivity.this);
                    db.open();
                    List<Map<String, Object>> list = db.querymainTable(TableMain.vin + "=?", new String[]{vin}, null, null);
                    if (list == null || list.size() == 0) {
                        Toast.makeText(MainActivity.this, "未查询到数据", 0).show();
                    } else {
                        Map<String, Object> data = null;
                        for (int i = 0; i < list.size(); i++) {//打印机序号和工位对比
                            if (Common.Printnum == Integer.valueOf((String) list.get(i).get(TableMain.station))) {
                                data = list.get(i);
                            }
                        }
                        if (data == null) {
                            Toast.makeText(MainActivity.this, "未查询到相关工位数据", 0).show();
                            return;
                        }
                        String result = data.get(TableMain.printdata).toString();
                        ServerSocket server = new ServerSocket();

                        if (server.ConnectServer(Common.Server_IP1, Common.Server_PORT)) {
                            server.SendDataToServer(String.valueOf(100000 + result.getBytes().length).substring(1, 6) + result);
                            server.close();
                        } else if (server.ConnectServer(Common.Server_IP2, Common.Server_PORT)) {
                            server.SendDataToServer(String.valueOf(100000 + result.getBytes().length).substring(1, 6) + result);
                            server.close();
                        } else {
                            Toast.makeText(MainActivity.this, "网络异常", 0).show();
                        }
                    }
                    db.close();
                }
            }
        });
        dialog.show();
    }

    /**
     * 解压assets目录下的EOL_DOWNLINE压缩包文件
     */
    private void performUnzipOperation()  {
        DirectoryUnZipper directoryUnZipper = new DirectoryUnZipper(this, "EOL_DOWNLINE.zip", outputDirectory);
        directoryUnZipper.execute();
        // 将解压缩操作已执行的标志保存到 SharedPreferences 中
        DirectoryUnZipper.setUnzipDone(this, true);
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == STORAGE_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了权限，继续执行你的逻辑
                initView();
            } else {
                // 权限被拒绝，你可能需要向用户解释为什么你的应用需要这个权限
                Toast.makeText(this, getResources().getString(R.string.open_storage_permission), Toast.LENGTH_LONG);
                finish();
            }
        }
    }

}
